
import React, { useEffect, useState } from 'react';
import styled from 'styled-components'
import { ListTable, ListColumn, Menu } from '@visactor/react-vtable';
import * as VTable from '@visactor/vtable';
import { Pagination } from 'antd';
import { EditableTableColumn, PaginationState, SortingState } from '.';
import * as VTable_editors from '@visactor/vtable-editors';
import { ValueType, valueTypeToString } from '../../../services';
import { VTableTimestampEditor } from './vtable-editor';

const input_editor = new VTable_editors.InputEditor();
const text_editor = new VTable_editors.TextAreaEditor();
const date_input_editor = new VTable_editors.DateInputEditor();
const list_editor = new VTable_editors.ListEditor({ values: ['girl', 'boy'] });
const timestamp_editor = new VTableTimestampEditor({ valueType: ValueType.String });

VTable.register.editor('string-editor', input_editor);
VTable.register.editor('text-editor', text_editor);
VTable.register.editor('blob-editor', input_editor);
VTable.register.editor('datetime-editor', date_input_editor);
VTable.register.editor('date-editor', date_input_editor);
VTable.register.editor('boolean-editor', input_editor);
VTable.register.editor('int-editor', input_editor);
VTable.register.editor('unit-editor', input_editor);
VTable.register.editor('long-editor', input_editor);
VTable.register.editor('ulong-editor', input_editor);
VTable.register.editor('float-editor', input_editor);
VTable.register.editor('double-editor', input_editor);
VTable.register.editor('timestamp-editor', timestamp_editor);

const getEditorByValueType = (column: EditableTableColumn, valueType: ValueType, valueLength?: number): string => {

    //是否需要进行下拉框渲染
    let typeStr = valueTypeToString(valueType);
    console.log(column);

    if (column && column.columnType && (column.columnType == 'text' || column.columnType == 'mediumtext')) {
        return `text-editor`;
    }

    return `${typeStr.toLowerCase()}-editor`;
};

const getTableColumns = (columns: Array<EditableTableColumn>) => {

    let cols = columns.map((column, index) => {
        if (column.readOnly) {
            return {
                title: column.title || column.name,
                field: column.name,
            };
        }
        let valueType = column.valueType;
        let editor = 'input-editor';
        if (valueType) {
            //
            editor = getEditorByValueType(column, valueType, column.valueLength);
        }
        //
        return {
            title: column.title || column.name,
            field: column.name,
            editor: editor
        };
    });

    return cols;
};

export const EditableTable = (props: {
    columns: Array<EditableTableColumn>,
    rowKey?: string,
    header?: () => React.ReactNode,
    pagination?: boolean,
    sorting?: boolean,
    selection?: boolean,
    columnOrder?: boolean,
    onStateChange?: (state: {
        rowSelection: any,
        pagination: PaginationState,
        sorting: SortingState,
        columnVisibility: any,
        columnOrder: any,
        data: Array<any>,
        total: number,
    }) => Promise<void> | void,
    version?: number,
    tableRef?: (table: any) => void;
    request: (pagination: PaginationState, columnOrder: string[], sorting: SortingState) => Promise<{ data: Array<any>, total: number }>,
    onSave?: (rowIndex: number, columnId: string, value: unknown, data: { [key: string]: any }) => Promise<boolean>,
    onClickCell?: (rowIndex: number, columnIndex: number, columnId: string, data: { [key: string]: any }) => Promise<void> | void,
    footer?: () => React.ReactNode
}) => {

    const [columns, setColumns] = useState<Array<any>>(getTableColumns(props.columns));

    const [data, setData] = useState<Array<any>>([]);

    const [total, setTotal] = useState<number>(0);

    const [columnOrder, setColumnOrder] = useState<string[]>(props.columns.map(c => c.id!));

    const [columnVisibility, setColumnVisibility] = useState({});

    const [sorting, setSorting] = useState<SortingState>([]);

    const [rowSelection, setRowSelection] = useState({})

    const [pagination, setPagination] = useState<PaginationState>({
        pageIndex: 0,
        pageSize: 20,
    });

    useEffect(() => {
        setColumns(getTableColumns(props.columns));
    }, [props.columns]);

    useEffect(() => {
        props.request(pagination, columnOrder, sorting).then((data) => {
            console.log(data);
            setData(data.data);
            setTotal(data.total);
        }).catch((err) => { console.log(err); });
    }, [pagination, columnOrder, sorting, props.version]);

    return (
        <Container>
            {
                props.header && props.header()
            }
            <TableContainer>
                <ListTable
                    records={data}
                    columns={columns}
                    widthMode={'autoWidth'}
                    heightMode={'autoHeight'}
                    theme={VTable.themes.DEFAULT}
                    defaultRowHeight={36}
                    editCellTrigger={'doubleclick'}
                    onDropdownMenuClick={(args) => {
                        console.log('onDropdownMenuClick', args)
                    }}
                    onClickCell={(args) => {
                        //{col: 3, row: 2, field: "notnull", cellHeaderPaths: Object, title: "notnull", …}
                        props.onClickCell && props.onClickCell(args.row - 1, args.col, columns[args.col].field, {
                            ...args.originData
                        })
                    }}
                    onChangCellValue={(args) => {
                        //{col: 2, row: 1, rawValue: "id", currentValue: "Id3", changedValue: "id3"}
                        console.log(args);
                        props.onSave && props.onSave(args.row - 1, columns[args.col].field, args.changedValue,
                            { ...args, name: columns[args.col].field, ...data[args.row - 1] }
                        ).then(() => {

                        }).catch((err) => {
                            console.log('编辑单元格异常:', err);
                        })
                    }}
                >
                </ListTable>
            </TableContainer>

            {
                props.pagination || props.footer ? (
                    <FooterContainer>
                        {
                            props.footer && props.footer()
                        }
                        {
                            props.pagination && (
                                <PaginationContainer>
                                    <Pagination
                                        total={total}
                                        size={'small'}
                                        showSizeChanger
                                        // showQuickJumper
                                        showTotal={(total) => `共${total}`}
                                        onShowSizeChange={(current, size) => {
                                            setPagination({ ...pagination, pageSize: size });
                                        }}
                                        onChange={(page, pageSize) => {
                                            setPagination({
                                                pageIndex: page - 1,
                                                pageSize
                                            });
                                        }}
                                    />
                                </PaginationContainer>
                            )
                        }
                    </FooterContainer>
                ) : (<></>)
            }
        </Container>
    );
}

const Container = styled.div`
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
`;

const TableContainer = styled.div`
    width: 100%;
    flex: 1;
    min-height: 200px;
    overflow: hidden;
`;

const FooterContainer = styled.div`
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top:1px solid #DFDFDF;
`;

const PaginationContainer = styled.div`
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top:1px solid #DFDFDF;
`;
